package com.ming.service.impl;

import com.ming.mapper.EmpExprMapper;
import com.ming.pojo.entity.EmpExpr;
import com.ming.service.EmpExprService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class EmpExprServiceImpl implements EmpExprService {

    @Autowired
    private EmpExprMapper empExprMapper;

    @Override
    public List<EmpExpr> getByEmpId(Integer empId) {
        return empExprMapper.getByEmpId(empId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(EmpExpr empExpr) {
        log.info("开始添加工作经历事务，员工ID: {}", empExpr.getEmpId());

        try {
            empExprMapper.insert(empExpr);
            log.info("工作经历添加成功，ID: {}", empExpr.getId());
        } catch (Exception e) {
            log.error("添加工作经历失败，事务回滚", e);
            throw e; // 重新抛出异常以触发事务回滚
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(EmpExpr empExpr) {
        log.info("开始更新工作经历事务，ID: {}", empExpr.getId());

        try {
            empExprMapper.update(empExpr);
            log.info("工作经历更新成功，ID: {}", empExpr.getId());
        } catch (Exception e) {
            log.error("更新工作经历失败，事务回滚，ID: {}", empExpr.getId(), e);
            throw e; // 重新抛出异常以触发事务回滚
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteById(Integer id) {
        log.info("开始删除工作经历事务，ID: {}", id);

        try {
            empExprMapper.deleteById(id);
            log.info("工作经历删除成功，ID: {}", id);
        } catch (Exception e) {
            log.error("删除工作经历失败，事务回滚，ID: {}", id, e);
            throw e; // 重新抛出异常以触发事务回滚
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteByEmpId(Integer empId) {
        log.info("开始删除员工所有工作经历事务，员工ID: {}", empId);

        try {
            empExprMapper.deleteByEmpId(empId);
            log.info("员工工作经历删除成功，员工ID: {}", empId);
        } catch (Exception e) {
            log.error("删除员工工作经历失败，事务回滚，员工ID: {}", empId, e);
            throw e; // 重新抛出异常以触发事务回滚
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addBatch(List<EmpExpr> empExprList) {
        if (empExprList == null || empExprList.isEmpty()) {
            return;
        }

        log.info("开始批量添加工作经历事务，数量: {}", empExprList.size());

        try {
            empExprMapper.insertBatch(empExprList);
            log.info("批量工作经历添加成功，数量: {}", empExprList.size());
        } catch (Exception e) {
            log.error("批量添加工作经历失败，事务回滚", e);
            throw e; // 重新抛出异常以触发事务回滚
        }
    }
}